package com.bomb.voice.feature.operationAccount;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.bomb.voice.MyApp;
import com.bomb.voice.R;
import com.bomb.voice.backNet.AddAccountBean;
import com.bomb.voice.bean.MyUser;
import com.bomb.voice.net.HttpSubscriber;
import com.bomb.voice.net.request.VoiceLoader;
import com.bomb.voice.utils.AccountConfig;
import com.feiyucloud.sdk.FYCall;
import com.feiyucloud.sdk.FYCallListener;
import com.feiyucloud.sdk.FYClient;
import com.feiyucloud.sdk.FYClientListener;
import com.feiyucloud.sdk.FYError;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.vipheyue.fastlib.utils.SharePreferencesUtil;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.bomb.voice.net.NetConfig.FY_APPID;
import static com.bomb.voice.net.NetConfig.FY_APPTOKEN;
import static com.feiyucloud.sdk.FYCall.SHOW_NUMBER_OFF;

public class FaceTimeActivity extends AppCompatActivity {
    private static final String TAG = "FaceTimeActivity";
    @Bind(R.id.et_phoneNumber)
    EditText et_phoneNumber;
    @Bind(R.id.activity_add_account)
    LinearLayout activity_add_account;
    @Bind(R.id.tv_panel)
    TextView tv_panel;
    @Bind(R.id.toggle_btn)
    ToggleButton toggle_btn;
    @Bind(R.id.tv_remaincall_tip)
    TextView tv_remaincall_tip;
    private Subscription subscribe;
    StringBuffer stringBuffer = new StringBuffer();
    String installationId = BmobInstallation.getCurrentInstallation().getInstallationId();
    String fyAccountId = SharePreferencesUtil.getSpString("fyAccountId", "", MyApp.get());
    String fyAccountPwd = SharePreferencesUtil.getSpString("fyAccountPwd", "", MyApp.get());

    private SVProgressHUD svProgressHUD;


    private AlertDialog mAlertView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_time);
        ButterKnife.bind(this);
        FYClient.instance().init(getApplicationContext(), "test", true, true);

        RxPermissions.getInstance(this)
                .request(AccountConfig.REQUIRED_PERMISSIONS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            initView();
                        } else {
                            Toast.makeText(FaceTimeActivity.this, "请同意权限否则无法正常使用APP", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    private void initView() {

        String phoneNumber = SharePreferencesUtil.getSpString("phoneNumber", "", this);
        et_phoneNumber.setText(phoneNumber);
        tv_panel.setMovementMethod(ScrollingMovementMethod.getInstance());
        svProgressHUD = new SVProgressHUD(FaceTimeActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("连接失败!!点击重试,或者重启应用").setPositiveButton("重试", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                initIntent();

            }
        });
        mAlertView = builder.create();

        toggle_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    startCall();
                } else {
                    endCall();
                }
            }
        });
        initIntent();

    }


    private void initIntent() {
        svProgressHUD.showWithStatus("连接网络电话服务器中...");

        if (TextUtils.isEmpty(fyAccountId)) {
            createFyAccount();
        } else {
            loginBmob();
        }
    }

    private void loginBmob() {
        MyUser bu2 = new MyUser();
        bu2.setUsername(installationId);    //默认以设备的installationId为用户名
        bu2.setPassword(AccountConfig.defaultAccountPwd);//密码也是默认
        bu2.login(listener);
    }

    private void createFyAccount() {
        VoiceLoader voiceBackLoader = new VoiceLoader();
        voiceBackLoader.addAccount(installationId).subscribe(new HttpSubscriber<AddAccountBean>() {
            @Override
            public void onNext(AddAccountBean addAccountBean) {
                //得到 飞语账户和名字 通过 resultMsg 判断 需要注册还是登录
                AddAccountBean.ResultBean result = addAccountBean.getResult();

                fyAccountId = result.getFyAccountId();
                fyAccountPwd = result.getFyAccountPwd();
                SharePreferencesUtil.putSpString("fyAccountId", fyAccountId, MyApp.get());
                SharePreferencesUtil.putSpString("fyAccountPwd", fyAccountPwd, MyApp.get());
                registerBmobAccount(fyAccountId, fyAccountPwd);
            }

            @Override
            public void onError(Throwable throwable) {
                super.onError(throwable);
                if (svProgressHUD.isShowing()) {
                    svProgressHUD.dismiss();
                }
            }
        });
    }

    private void dealWithError(String localizedMessage) {
        svProgressHUD.dismiss();
        mAlertView.show();
        Toast.makeText(this, localizedMessage, Toast.LENGTH_SHORT).show();
    }

    private void registerBmobAccount(String voiceID, String voicePwd) {
        MyUser bu = new MyUser(voiceID, voicePwd, AccountConfig.defaultRemainCallTimes);
        bu.setUsername(installationId);    //默认以设备的installationId为用户名
        bu.setPassword(AccountConfig.defaultAccountPwd);//密码也是默认
//注意：不能用save方法进行注册
        bu.signUp(listener);
    }


    SaveListener<MyUser> listener = new SaveListener<MyUser>() {
        @Override
        public void done(MyUser myUser, BmobException e) {
            if (e == null) {
                tv_remaincall_tip.setText("剩余次数:" + myUser.getRemainCallTimes());
                loginFy();
            } else {
                dealWithError(e.getLocalizedMessage());
            }
        }
    };

    public void loginFy() {
        FYClient.addListener(new FYClientListener() {
            @Override
            public void onConnectionSuccessful() {
                svProgressHUD.showSuccessWithStatus("连接成功！输入号码开始拨打吧");
            }

            @Override
            public void onConnectionFailed(FYError fyError) {
                if (svProgressHUD.isShowing()) {
                    svProgressHUD.dismiss();
                }
                mAlertView.show();
            }
        });
        FYCall.addListener(new FYCallListener() {
            @Override
            public void onCallFailed(FYError fyError) {
//                Toast.makeText(FaceTimeActivity.this, "onCallFailed" + fyError.msg, Toast.LENGTH_SHORT).show();
                recordInfo("onCallFailed 呼叫失败" + fyError.msg);
            }

            @Override
            public void onIncomingCall(String s) {
                Toast.makeText(FaceTimeActivity.this, "onIncomingCall" + s, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onOutgoingCall(String s) {
//                Toast.makeText(FaceTimeActivity.this, "onOutgoingCall" + s, Toast.LENGTH_SHORT).show();
                recordInfo("外拨电话" + s);

            }

            @Override
            public void onCallRunning(String s) {
//                Toast.makeText(FaceTimeActivity.this, "FYCall 正在通话" + s, Toast.LENGTH_SHORT).show();
                recordInfo("FYCall 正在通话" + s);
                FYCall.instance().setMuteEnabled(false);//麦克风静音
            }

            @Override
            public void onCallEnd() {
//                Toast.makeText(FaceTimeActivity.this, "onCallEnd 通话结束", Toast.LENGTH_SHORT).show();
                recordInfo("onCallEnd 通话结束");

            }

            @Override
            public void onCallbackSuccessful() {
                Toast.makeText(FaceTimeActivity.this, "onCallbackSuccessful", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCallbackFailed(FYError fyError) {
                Toast.makeText(FaceTimeActivity.this, "onCallbackFailed" + fyError.msg, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCallAlerting(String s) {
                recordInfo("FYCall 对方正在振铃" + s);

            }

            @Override
            public void onDtmfReceived(char c) {
                Toast.makeText(FaceTimeActivity.this, "FYCall" + c, Toast.LENGTH_SHORT).show();
            }
        });

        FYClient.instance().connect(FY_APPID, FY_APPTOKEN, fyAccountId, fyAccountPwd);
        FYCall.instance().setMuteEnabled(false);//麦克风静音


    }


    public void startCall() {
        final String info = et_phoneNumber.getText().toString().trim();
        SharePreferencesUtil.putSpString("phoneNumber", info, this);
        recordInfo("两分钟后自动开始轮循呼叫,最新应用 请关注 微信公众号: wBook 可以直接发送消息" );
        /**
         * 网络直拨
         *
         * @param number 被叫的飞语云账户ID（必须绑定过手机号码）或手机号码
         * @param showNumberType 显号类型 {@link #SHOW_NUMBER_DEFAULT}，
         *                  {@link #SHOW_NUMBER_ON}， {@link #SHOW_NUMBER_OFF}
         * @param isRecord 是否录音
         * @param extraData 自定义透传信息(能透传给AS服务器)
         */
        Observable<Long> delay = Observable
                .interval(2, TimeUnit.MINUTES)
//                .interval(3, TimeUnit.SECONDS)
                .take(720)
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        FYCall.instance().directCall(info, SHOW_NUMBER_OFF, false, null);
                        return aLong;
                    }
                })
                .delay(40, TimeUnit.SECONDS)
                ;

        subscribe = delay.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(new HttpSubscriber<Long>() {
                    @Override
                    public void onNext(Long callTimes) {
                        //记录到 bmob 拨打次数
                        if (callTimes % 10 == 0) {
                            updateBmobRecord();
                        }

                        recordInfo("拨打次数:" + callTimes);
                        if (FYCall.instance().isInCall()) {
                            FYCall.instance().endCall();
                        }
                    }
                });
    }

    private void updateBmobRecord() {
        BmobQuery<MyUser> query = new BmobQuery<MyUser>();
        query.addWhereEqualTo("username", installationId);
        query.findObjects(new FindListener<MyUser>() {
            @Override
            public void done(List<MyUser> userList, BmobException e) {
                if (e == null) {
                    MyUser queryUser = userList.get(0);
                    int remainCallTimes = queryUser.getRemainCallTimes();

                    if (remainCallTimes < 0) {
                        endCall();
                        recordInfo("请充值后再使用");
                    }
                    tv_remaincall_tip.setText("剩余次数:" + remainCallTimes);
                    remainCallTimes -= 10;

                    MyUser netUser = new MyUser();
                    netUser.setRemainCallTimes(remainCallTimes);
                    netUser.update(queryUser.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
//                                Toast.makeText(FaceTimeActivity.this, "更新成功", Toast.LENGTH_SHORT).show();

                            }else{
//                                Toast.makeText(FaceTimeActivity.this, "更新失败", Toast.LENGTH_SHORT).show();

                            }
                        }
                    });
                } else {
                    Toast.makeText(FaceTimeActivity.this, "查询用户当前余额失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void recordInfo(String info) {
        final Calendar mCalendar = Calendar.getInstance();
        int hour = mCalendar.get(Calendar.HOUR);
        int min = mCalendar.get(Calendar.MINUTE);
        String nowTime = "   时间 " + hour + ":" + min;
        stringBuffer.insert(0, info + nowTime + "\n\r");
        tv_panel.setText(stringBuffer.toString());
    }

    public void endCall() {
        recordInfo("已经手动停止呼叫");
        if (subscribe != null) {
            subscribe.unsubscribe();
        }
        if (FYCall.instance().isInCall()) {
            FYCall.instance().endCall();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FYClient.instance().disconnect();

    }

    public void recharge(View view) {
        startActivity(new Intent(this, RechargeActivity.class));
    }
}
